// components/ani-tab-swiper/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    list:Array
  },

  /**
   * 组件的初始数据
   */
  data: {
    	scrollLeft: 0,
		groupIndex:0,
		smIndex:0,
		swiperCurrIndex:0,
		tabBg:{
			width:0,
			left:0
		}
  },
  lifetimes:{
    ready(){
      this.toScroll(0)
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    initBg(){

    },
    tab(e){
      const {index}=e.currentTarget.dataset;
      const swiperCurrIndex=this.data.list.reduce((prev,item,indexs)=>
      indexs>=index?prev: prev+item.list.length
      ,0)
      this.setData({swiperCurrIndex})
    },
    changeSwiper(e){
      const swiperCurrIndex=e.detail.current
      let groupIndex=null;
      let smIndex=null;
      this.data.list.reduce((prev,item,index)=>{
        if(prev===false) return prev
        const allIndex=prev+item.list.length
        smIndex=swiperCurrIndex-prev
        if(allIndex>swiperCurrIndex){
          groupIndex=index
          return false
        }
        return allIndex
      },0)
      this.toScroll(groupIndex)
      this.setData({
        swiperCurrIndex,
        groupIndex,
        smIndex
      })
    },
    toScroll(index) {
      const {
        windowWidth
      } = wx.getSystemInfoSync();
      // const index = this.data.indexs;
	  if (index >= this.data.list.length) return
	  
	  this.getAllTabPosition(res=>{
		const thisWidth = res[0][index].width;
		const margin=20;
    const allLeft = res[0].filter((x, i) => i < index).reduce((prv, x, i) => prv + x.width + margin, 0);
    const scrollLeft = allLeft - (windowWidth - thisWidth) / 2 + margin;
    this.setData({
		  scrollLeft: scrollLeft,
		  tabBg:{
			  width:thisWidth+margin,
			  left:allLeft+margin/2
		  }
        })
	  })
	},
	getAllTabPosition(callback){
		const query = wx.createSelectorQuery().in(this)
		  query.selectAll('.items').boundingClientRect()
		  query.selectViewport()
		  query.exec((res) => {
			callback(res)
		  })
	  
	  }
  },
 
})
